﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace thailandProject.Models
{
    /// <summary>
    /// Provides a wrapper class that contains information about
    /// a list's page size, the page number, and what page the
    /// list is currently on
    /// </summary>
    public class PagedList<T> : List<T>
    {
        public int pageSize;
        public int pageNumber; //1 will be the first page

        public bool hasNextPage = true;
        public bool hasPreviousPage = true;

        public int pageMin;
        public int pageMax;

        /// <summary>
        /// Converts an IEnumerable list into a PagedList.
        /// </summary>
        /// <param name="pageSize">The number of items that can appear on a page</param>
        /// <param name="pageNumber">The current page the list is displaying</param>
        /// <returns>A converted PagedList</returns>
        public static PagedList<T> toPagedList(List<T> list, int pageSize, int pageNumber)
        {
            PagedList<T> rt = new PagedList<T>();

            try
            {
                if (pageSize < 1)
                    throw new ArgumentException("pageSize must be greater than 0");
                if (pageNumber > (list.Count / pageSize) + 1)
                {
                    pageNumber = 1; //Rather than crash, reset the page number
                    //throw new IndexOutOfRangeException("pageNumber exceeds possible pages");
                }

                rt.pageSize = pageSize;
                rt.pageNumber = pageNumber;

                int maxPageSize = (list.Count - 1) / pageSize + 1;

                if (pageNumber == maxPageSize)
                    rt.hasNextPage = false;
                if (pageNumber == 1)
                    rt.hasPreviousPage = false;

                for (int i = pageSize * (pageNumber - 1); i < pageSize * pageNumber && i < list.Count; i++)
                {
                    rt.Add(list[i]);
                }

                //Determine the amount of pages to show. By default, a maximum of ten numbers will show centered
                //around the current value
                rt.pageMin = pageNumber - 5 >= 1 ? pageNumber - 5 : 1;
                rt.pageMax = rt.pageMin + 10 <= (list.Count / pageSize) + 1 ? rt.pageMin + 10 : (list.Count / pageSize) + 1;
            }
            catch (Exception ex)
            {
                ErrorLog.logError(ex);
            }

            return rt;
        }
    }
}